﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dao;

namespace Web.Page
{
    public partial class CGD_Add : BasePage
    {
        Departments_Dao dao = new Departments_Dao();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.lblTitle.Text = "新增采购单";
                this.tbRQ.Attributes.Add("onclick", "show()");         
                this.lblTitle2.Text = "新增采购单明细";
                initValue();

                #region 节点
                Department dept = dao.GetRoot();
                if (dept == null)
                {
                    return;
                }
                TreeNode root = new TreeNode();
                root.Text = dept.Name;
                root.Value = dept.Id.ToString();
                root.PopulateOnDemand = true;
                //root.NavigateUrl = string.Format("DepartmentEdit.aspx?id={0}", root.Value);
                root.ImageUrl = "../images/user/group.png";
                tvOrg.Nodes.Add(root);
                #endregion
            }
        }

        private void initValue()
        {
            // 部门
            //Departments_Dao daoDep = new Departments_Dao();
            //List<Department> lsDep = daoDep.QueryAll();
            //this.ddlBM.DataSource = lsDep;
            //this.ddlBM.DataTextField = "Name";
            //this.ddlBM.DataValueField = "ID";
            //this.ddlBM.DataBind();
            //this.ddlBM.Items.Insert(0, new ListItem("请选择", "0"));

            // 供应商
            ZL_GYS_Dao daoGys = new ZL_GYS_Dao();
            List<ZL_GYS> lsGys = daoGys.QueryAll();
            this.ddlGYS.DataSource = lsGys;
            this.ddlGYS.DataTextField = "MC";
            this.ddlGYS.DataValueField = "ID";
            this.ddlGYS.DataBind();
            this.ddlGYS.Items.Insert(0, new ListItem("请选择", "0"));

            // 单位
            CS_JBDW_Dao daoDw = new CS_JBDW_Dao();
            List<CS_JBDW> listDw = daoDw.Query4WL();
            this.ddlDWBH.DataSource = listDw;
            this.ddlDWBH.DataTextField = "MC";
            this.ddlDWBH.DataValueField = "BH";
            this.ddlDWBH.DataBind();
            this.ddlDWBH.Items.Insert(0, new ListItem("请选择", "0"));
        }

        /// <summary>
        /// 清空所有TextBox内容
        /// </summary>
        private void ClearControlsValue()
        {
            //this.ddlBM.SelectedIndex = 0;
            //this.ddlRY.SelectedIndex = 0;
            this.txtbm.Text = "";
            this.txtry.Text = "";
            this.ddlGYS.SelectedIndex = 0;
            this.tbRQ.Text = "";
            this.lbResult.Text = "";

            this.ddlDWBH.SelectedIndex = 0;
            this.ddlWPID.SelectedIndex = 0;
            this.ddlWPLX.SelectedIndex = 0;
            this.tbDJ.Text = "";
            this.tbSL.Text = "";
            this.lbResult.Text = "";
        }

        //protected void ddlBM_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    this.ddlRY.Items.Clear();
        //    string depId = ddlBM.SelectedValue;
        //    if (depId != "0")
        //    {
        //        Guid guid = Guid.Parse(depId);
        //        using (var context = new Dao.ErpEntities())
        //        {
        //            var query = from d in context.UserInDepartmentSet
        //                        join u in context.UserSet
        //                        on d.UserId equals u.Id
        //                        where d.DepartmentId == guid
        //                        select new
        //                        {
        //                            Id = d.UserId,
        //                            Name = u.Name
        //                        };
        //            List<UserNames> list = new List<UserNames>();
        //            if (query.Count() > 0)
        //            {
        //                foreach (var q in query)
        //                {
        //                    UserNames un = new UserNames();
        //                    un.Id = q.Id.ToString();
        //                    un.Name = q.Name;
        //                    list.Add(un);
        //                }
        //            }

        //            this.ddlRY.DataSource = list;
        //            this.ddlRY.DataTextField = "Name";
        //            this.ddlRY.DataValueField = "Id";
        //            this.ddlRY.DataBind();
        //        }
        //    }

        //    this.ddlRY.Items.Insert(0, new ListItem("请选择", "0"));
        //}

        protected void ddlWPLX_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlWPID.Items.Clear();
            string wplx = this.ddlWPLX.SelectedValue.Trim();

            List<IdNames> list = new List<IdNames>();
            // 物料
            if (wplx == "01")
            {
                ZL_WL_Dao daoWl = new ZL_WL_Dao();
                List<ZL_WL> listwl = daoWl.QueryAll();
                foreach (ZL_WL wl in listwl)
                {
                    IdNames n = new IdNames();
                    n.Id = wl.ID.ToString();
                    n.Name = wl.MC;
                    list.Add(n);
                }
            }
            else if (wplx == "02")
            {
                ZL_CP_Dao daoCp = new ZL_CP_Dao();
                List<ZL_CP> listcp = daoCp.QueryAll();
                foreach (ZL_CP cp in listcp)
                {
                    IdNames n = new IdNames();
                    n.Id = cp.ID.ToString();
                    n.Name = cp.BH;
                    list.Add(n);
                }
            }

            this.ddlWPID.DataSource = list;
            this.ddlWPID.DataTextField = "Name";
            this.ddlWPID.DataValueField = "Id";
            this.ddlWPID.DataBind();
            this.ddlWPID.Items.Insert(0, new ListItem("请选择", "0"));
        }

        private void LoadChildNode(TreeNode node)
        {
            List<Department> ds = dao.GetChildren(node.Value);
            foreach (Department dept in ds)
            {
                TreeNode child = new TreeNode();
                child.Text = dept.Name;
                child.Value = dept.Id.ToString();
                child.PopulateOnDemand = true;
                //child.NavigateUrl = string.Format("DepartmentEdit.aspx?id={0}", child.Value);
                child.ImageUrl = "../images/user/group.png";                
                node.ChildNodes.Add(child);
            }
        }

        private void LoadUsers(TreeNode node)
        {
            List<User> us = dao.GetUsers(node.Value);
            foreach (User u in us)
            {
                TreeNode child = new TreeNode();
                child.Text = u.Name;
                child.Value = u.Id.ToString();
                child.PopulateOnDemand = true;
                //child.NavigateUrl = string.Format("UserEdit.aspx?id={0}", child.Value);
                child.ImageUrl = "../images/user/user.png";
                child.Expanded = true;               
                node.ChildNodes.Add(child);
            }
        }

        protected void tvOrg_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            //if (IsCallback)
            //{
            if (e.Node.ChildNodes.Count == 0)
            {
                LoadChildNode(e.Node);
                LoadUsers(e.Node);
            }
            //}
        }
        
        protected void tvOrg_SelectedNodeChanged(object sender, EventArgs e)
        {
            Users_Dao user_Dao = new Users_Dao();
            User user = user_Dao.Query(tvOrg.SelectedNode.Value);//确定是否为人员
            
            departmentsUsers du = new departmentsUsers();
            du.users = this.txtry.Text = "";
            du.usersID = "";
            du.departments = this.txtbm.Text = "";
            du.departmentsID = "";
            if (user!=null)
            {                
                du.users = this.txtry.Text = tvOrg.SelectedNode.Text;
                du.usersID = tvOrg.SelectedNode.Value;
                du.departments = this.txtbm.Text = tvOrg.SelectedNode.Parent.Text;
                du.departmentsID = tvOrg.SelectedNode.Parent.Value;
            }
        }

        protected class departmentsUsers
        {
            public string users { get; set; }
            public string usersID { get; set; }
            public string departments { get; set; }
            public string departmentsID { get; set; }
        }

        protected class UserNames
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }

        protected class IdNames
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }

        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            this.lbResult.Text = "";
            //if (this.ddlBM.SelectedValue.Equals("0"))
            //{
            //    this.lbResult.Text = "请选择部门";
            //    return;
            //}
            //if (this.ddlRY.SelectedValue.Equals("0"))
            //{
            //    this.lbResult.Text = "请选择人员";
            //    return;
            //}
            if (this.txtbm.Equals("0"))
            {
                this.lbResult.Text = "请选择部门";
                return;
            }
            if (this.txtry.Equals("0"))
            {
                this.lbResult.Text = "请选择人员";
                return;
            }
            if (this.ddlGYS.SelectedValue.Equals("0"))
            {
                this.lbResult.Text = "请选择供应商";
                return;
            }

            if (this.ddlWPLX.SelectedValue.Equals("0"))
            {
                return;
            }
            if (this.ddlWPID.SelectedValue.Equals("0"))
            {
                this.lbResult0.Text = "请选择物品";
                return;
            }
            if (this.ddlDWBH.SelectedValue.Equals("0"))
            {
                this.lbResult0.Text = "请选择单位";
                return;
            }
            Guid ID=Guid.NewGuid();
            departmentsUsers du = new departmentsUsers();
            CGD entity = new CGD()
            {
                ID = ID,
                //BMID = Guid.Parse(this.ddlBM.SelectedValue),
                //RYID = Guid.Parse(this.ddlRY.SelectedValue),
                BMID = Guid.Parse(du.departmentsID),
                RYID = Guid.Parse(du.usersID),
                RQ = DateTime.Parse(this.tbRQ.Text.Trim()),
                ZT = 0,
                CJSJ = DateTime.Now,
                GYSID = Guid.Parse(this.ddlGYS.SelectedValue)
            };

            CGDMXB entity2 = new CGDMXB()
            {
                ID = Guid.NewGuid(),
                WPID = Guid.Parse(ddlWPID.SelectedValue),
                WPLX = ddlWPLX.SelectedValue,
                SL = double.Parse(tbSL.Text.Trim()),
                DWBH = ddlDWBH.SelectedValue,
                DJ = float.Parse(tbDJ.Text.Trim()),
                CGDID = ID
            };

            string resultMessage = "";
            try
            {
                CGD_Dao dao = new CGD_Dao();
                int result = dao.Add(entity);

                CGDMXB_Dao dao2 = new CGDMXB_Dao();
                result += dao2.Add(entity2);

                if (result == 2)
                {
                    resultMessage = "保存成功";
                    ClearControlsValue();
                }
            }
            catch (Exception ex)
            {
                resultMessage = "保存失败" + ex.Message;
            }
            finally
            {
                this.lbResult0.Text = resultMessage;
            }
        }

        protected void btnClear_Click(object sender, ImageClickEventArgs e)
        {
            ClearControlsValue();
        }

        protected void btnReturn_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("CGD_Query.aspx");
        }
    }
}